#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include "log.hpp"
#include <functional>
#include "InetAddr.hpp"
#include <cstring>
enum
{
    USAGE_ERROR = 1,
    SOCKET_ERROR,
    BING_ERROR
};

using hander_message_t = std::function<void(int sockfd, const std::string message, const InetAddr who)>;
const static int defaultfd = -1;
class UdpServer
{
public:
    UdpServer(uint16_t port, hander_message_t hander_message)
        : _port(port), _sockfd(defaultfd), _isruning(false), _hander_message(hander_message)
    {
    }
    void InitServer()
    {
        // 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error,%s,%d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success , sockfd:%d\n", _sockfd);

        // 2.0 填充sockaddr_in结构
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;//可以监听来自任意网络接口的数据包，只要是发送给端口_port的，告诉内核可以选择任何可用的本地ip地址来绑定套接字
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));//将套接字_sockfd与local结构体中指定的本地IP和端口号关联起来
        if (n < 0)
        {
            LOG(FATAL, "bind error,%s,%d\n", strerror(errno), errno);
            exit(BING_ERROR);
        }
        LOG(INFO, " socket bind success\n");
    }
    void Start()
    {
        _isruning = true;
        while (true)
        {
            char message[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer); // 必须初始化成为sizeof(peer)
            // 1. 我们要让server先收数据
            ssize_t n = recvfrom(_sockfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                message[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG, "get message from [%s:%d]: %s\n", addr.Ip().c_str(), addr.Port(), message);
                // bool ok;
                // std::string response = _func(request,ok);
                // std::cout<<"debug:1"<<std::endl;
                // 2. 我们要将server收到的数据，发回给对方
                _hander_message(_sockfd, message, addr);
                // sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
        _isruning = false;
    }
    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    bool _isruning;
    // 给服务器设置回调用来让上层进行注册业务的处理方法
    hander_message_t _hander_message;
};
